//
//  BIDHomeViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/16.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDHomeViewController.h"
#import "BIDHeaderViewForHomeView.h"
#import "BIDLoadWebPageViewController.h"
#import "BIDAnnouncementDetailViewController.h"
#import "BIDSlideShowDetailViewController.h"
#import "BIDServiceForResidentViewController.h"
#import "BIDFinanceDetailViewController.h"
#import "BIDFavorableInfoListViewController.h"
#import "BIDDealInfoViewController.h"

#import "BIDHouseListViewController.h"
#import "BIDPayListViewController.h"

#import "BIDHomeCell.h"
#import "BIDHeadlineView.h"
#import "BIDFunctionView.h"
#import "BIDConvenienceView.h"
#import "BIDPrivilegeAndDealView.h"
#import "BIDFinanceView.h"

//获取公告列表
static NSString *announcementListURL = @"afficheAndroid/list.action";
//轮播图详情
static NSString *slideshowDetailURL = @"advertisementAndroid/getById.action";
//公告详情
static NSString *announcementDetailURL = @"afficheAndroid/getById.action";
//金融理财详情
static NSString *financeDetailURL = @"financeAndroid/getById.action";

@interface BIDHomeViewController ()<BIDHeaderViewForHomeViewDelegate, UITableViewDelegate, UITableViewDataSource, BIDHeadlineViewDelegate, BIDFunctionViewDelegate, BIDPrivilegeAndDealDelegate, BIDFinanceViewDelegate>
{
    BIDHeaderViewForHomeView *_headerView;
    BOOL _bRegister;
    NSMutableArray *_dataSourceArr;
    NSArray *_noticeArr;
}
@end

@implementation BIDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [_tableView setBackgroundColor:RGBACOLOR(230.f, 230.f, 237.f, 1.0f)];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //_tableView.bounces = NO;
    [self createHeaderView];
    [self prepareForData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)prepareForData
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _noticeArr = @[];
    NSArray *arr = @[@[@{@"height":@44},
                       @{@"height":@164},
                       @{@"height":[NSNumber numberWithFloat:screenSize.width*39/160]},//便民服务
                       @{@"height":[NSNumber numberWithFloat:screenSize.width*3/16]},//优惠信息和交易信息
                       @{@"height":@98}],
                     @[]];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:arr];
    //
    [self fetchNotice];
}

/**
 获取当前用户已绑定的房屋列表
 */
- (void)fetchBindingHouse
{
}

- (void)createHeaderView
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDHeaderViewForHomeView" owner:self options:nil] lastObject];
    _headerView.delegate = self;
    CGRect headerViewFrame = _headerView.frame;
    headerViewFrame.origin.x = 0;
    headerViewFrame.origin.y = 0;
    headerViewFrame.size.width = screenSize.width;
    headerViewFrame.size.height = screenSize.width*209/320;
    _headerView.frame = headerViewFrame;
    _tableView.tableHeaderView = _headerView;
    _tableView.tableFooterView = [[UIView alloc] init];
}

/**
 获取通知内容（掌上头条）
 */
- (void)fetchNotice
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], announcementListURL];
        NSString *strPost = [[NSString alloc] initWithFormat:@"page=1&rows=3", [AppDelegate getUserId]];
        id obj = [BIDDataCommunication getDataFromNetBySyn:strRequestURL postValue:strPost];
        if(obj)
        {
            NSDictionary *responseDic = (NSDictionary *)obj;
            NSNumber *value = responseDic[@"head"][@"success"];
            if([value intValue] == 1)
            {
                _noticeArr = [[NSArray alloc] initWithArray:responseDic[@"body"][@"rows"]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }
        }
    });
}

#pragma mark - BIDHeaderViewForMainViewDelegate
- (void)loadContentWithAdvertisementID:(NSString *)advertisementID
{
    BIDSlideShowDetailViewController *vc = [[BIDSlideShowDetailViewController alloc] initWithNibName:@"BIDLoadWebPageViewController" bundle:nil];
    vc.requestURL = [[NSString alloc] initWithFormat:@"%@/%@?advertisement.id=%@", [AppDelegate getServerAddr], slideshowDetailURL, advertisementID];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDHeadlineViewDelegate
- (void)showHeadlineDetailWithDictionary:(NSDictionary *)dic
{
    NSDictionary *noticeDic = dic[@"notice"];
    BIDAnnouncementDetailViewController *vc = [[BIDAnnouncementDetailViewController alloc] initWithNibName:@"BIDLoadWebPageViewController" bundle:nil];
    vc.requestURL = [[NSString alloc] initWithFormat:@"%@/%@?affiche.id=%@", [AppDelegate getServerAddr], announcementDetailURL, dic[@"id"]];
    //
    NSString *strTitle = dic[@"title"];
    NSString *strCreator = dic[@"createUserName"];
    NSString *strDate = dic[@"createTime"];
    NSDateFormatter *dateFormatter = [NSDateFormatter defaultDateFormatter];
    NSDate *date = [dateFormatter dateFromString:strDate];
    NSString *strFormatDate = [date formattedDateDescription];
    NSString *strPublishInfo = [[NSString alloc] initWithFormat:@"发布人:%@   %@", strCreator, strFormatDate];
    NSMutableString *strExternalContent = [NSMutableString string];
    if(strTitle.length > 0)
    {
        [strExternalContent appendFormat:@"<p style='margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: normal; color: rgb(0, 0, 0); font-size: 20px; line-height: normal; font-family: 微软雅黑; font-weight:900, widows: 1;'>%@</p>", strTitle];
    }
    if(strPublishInfo.length > 0)
    {
        [strExternalContent appendFormat:@"<p style='margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: normal; color: rgb(0, 0, 0); font-size: 11px; line-height: normal; font-family: 微软雅黑; widows: 1;'>%@</p><br/>", strPublishInfo];
    }
    vc.externalContent = strExternalContent;
    //
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDFunctionViewDelegate
- (void)openModuleWithClassName:(NSString *)className andXib:(BOOL)isNeedXib bindingHouse:(BOOL)isNeedBindingHouse
{
    UIViewController *vc = nil;
    NSArray *arr = [AppDelegate getBindingHouse];
    if(isNeedBindingHouse)
    {
        if(arr.count == 0)
        {
            [self showAlertView:@"请先绑定房屋" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            return;
        }
    }
    if([className isEqualToString:@"BIDPayListViewController"])
    {
        //缴费,先判断是否需要显示房屋列表
        NSArray *arr = [AppDelegate getBindingHouse];
        if(arr.count > 1)
        {
            //名下多于一套房屋时先显示房屋列表
            vc = [[BIDHouseListViewController alloc] init];
        }
        else
        {
            //只有一套房屋时直接显示费用列表
            vc = [[BIDPayListViewController alloc] initWithNibName:@"BIDPayListViewController" bundle:nil];
        }
    }
    else
    {
        if(isNeedXib)
        {
            vc = [[NSClassFromString(className) alloc] initWithNibName:className bundle:nil];
        }
        else
        {
            vc = [[NSClassFromString(className) alloc] init];
        }
    }
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDPrivilegeAndDealDelegate
- (void)showPrivilegeInfo
{
    //显示优惠信息
    NSLog(@"show privilege info");
    BIDFavorableInfoListViewController *vc = [[BIDFavorableInfoListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showDealInfo
{
    //显示交易信息
    NSLog(@"show deal info");
    BIDDealInfoViewController *vc = [[BIDDealInfoViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BIDFinanceViewDelegate
- (void)loadContentWithFinanceID:(NSString *)financeID
{
    BIDFinanceDetailViewController *vc = [[BIDFinanceDetailViewController alloc] initWithNibName:@"BIDLoadWebPageViewController" bundle:nil];
    vc.requestURL = [[NSString alloc] initWithFormat:@"%@/%@?finance.id=%@", [AppDelegate getServerAddr], financeDetailURL, financeID];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataSourceArr[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDHomeCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"homeCell"];
    }
    switch(section)
    {
        case 0:
        {
            NSNumber *heightValue = _dataSourceArr[section][row][@"height"];
            CGFloat height = [heightValue floatValue];
            BIDHomeCell *homeCell = [tableView dequeueReusableCellWithIdentifier:@"homeCell"];
            if(row == 0)
            {
                //掌上头条
                BIDHeadlineView *subView = [homeCell.contentView viewWithTag:100];
                if(!subView)
                {
                    subView = [[[NSBundle mainBundle] loadNibNamed:@"BIDHeadlineView" owner:self options:nil] lastObject];
                    subView.tag = 100;
                    CGRect frame = subView.frame;
                    frame.origin.x = 5;
                    frame.origin.y = 5;
                    frame.size.width = CGRectGetWidth(tableView.frame)-10;
                    frame.size.height = height;
                    subView.frame = frame;
                    [homeCell.contentView addSubview:subView];
                }
                subView.delegate = self;
                if(_noticeArr.count > 0)
                {
                    [subView prepareData:_noticeArr];
                }
            }
            else if(row == 1)
            {
                //功能组
                BIDFunctionView *subView = [homeCell.contentView viewWithTag:101];
                if(!subView)
                {
                    subView = [[[NSBundle mainBundle] loadNibNamed:@"BIDFunctionView" owner:self options:nil] lastObject];
                    subView.tag = 101;
                    CGRect frame = subView.frame;
                    frame.origin.x = 5;
                    frame.origin.y = 5;
                    frame.size.width = CGRectGetWidth(tableView.frame)-10;
                    frame.size.height = height;
                    subView.frame = frame;
                    [homeCell.contentView addSubview:subView];
                }
                subView.delegate = self;
            }
            else if(row == 2)
            {
                //便民服务
                BIDConvenienceView *subView = [homeCell.contentView viewWithTag:102];
                if(!subView)
                {
                    subView = [[[NSBundle mainBundle] loadNibNamed:@"BIDConvenienceView" owner:self options:nil] lastObject];
                    subView.tag = 102;
                    CGRect frame = subView.frame;
                    frame.origin.x = 5;
                    frame.origin.y = 5;
                    frame.size.width = CGRectGetWidth(tableView.frame)-10;
                    frame.size.height = height;
                    subView.frame = frame;
                    [homeCell.contentView addSubview:subView];
                }
            }
            else if(row == 3)
            {
                //优惠信息和交易信息
                BIDPrivilegeAndDealView *subView = [homeCell.contentView viewWithTag:103];
                if(!subView)
                {
                    subView = [[[NSBundle mainBundle] loadNibNamed:@"BIDPrivilegeAndDealView" owner:self options:nil] lastObject];
                    subView.tag = 103;
                    CGRect frame = subView.frame;
                    frame.origin.x = 5;
                    frame.origin.y = 5;
                    frame.size.width = CGRectGetWidth(tableView.frame)-10;
                    frame.size.height = height;
                    subView.frame = frame;
                    [homeCell.contentView addSubview:subView];
                }
                subView.delegate = self;
            }
            else if(row == 4)
            {
                //金融理财
                BIDFinanceView *subView = [homeCell.contentView viewWithTag:103];
                if(!subView)
                {
                    subView = [[[NSBundle mainBundle] loadNibNamed:@"BIDFinanceView" owner:self options:nil] lastObject];
                    subView.tag = 103;
                    CGRect frame = subView.frame;
                    frame.origin.x = 5;
                    frame.origin.y = 5;
                    frame.size.width = CGRectGetWidth(tableView.frame)-10;
                    frame.size.height = height;
                    subView.frame = frame;
                    [homeCell.contentView addSubview:subView];
                }
                subView.delegate = self;
            }
            cell = homeCell;
        }
            break;
        case 1:
        {}
            break;
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    switch(indexPath.section)
    {
        case 0:
        {
            if(row == 2)
            {
                //便民服务模块
                BIDServiceForResidentViewController *vc = [[BIDServiceForResidentViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 1:
        {
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 44.f;
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    NSDictionary *dic = nil;
    if(section == 0)
    {
        dic = _dataSourceArr[section][row];
        NSNumber *value = dic[@"height"];
        height = [value integerValue];
        height += 10;
    }
    return height;
}

@end
